<template>
  <a-card>
    <TableSearch
      ref="tableSearch"
      :fields="fields"
      @searchEmit="searchEmit"
      @resetEmit="resetEmit"
      :isRefreshBtn="false"
      @refreshEmit="$refs.table.refresh()"
      :toolSettings="toolSettings"
    />
    <s-table
      ref="table"
      rowKey="id"
      :size="tableSize"
      :columns="columns"
      :data="tableData"
      :scroll="{ x: 1000 }"
      :onCompleted="onCompleted"
      :row-class-name="rowClassName"
    >
      <template slot="number" slot-scope="text">
        {{ text || '-' }}
      </template>
      <template slot="status" slot-scope="text">
        <a-tag v-if="text == 0" class="cursor" color="#52c41a">已出库</a-tag>
        <a-tag v-else class="cursor">未出库</a-tag>
      </template>
      <template slot="images" slot-scope="text">
        <span v-for="url in text" :key="url">
          <a-avatar
            @click="imagePreview(formatUrl(url))"
            :src="formatUrl(url)"
            shape="square"
            :size="32"
            style="cursor: pointer;border: 1px solid #ccc"
          />
          &nbsp;
        </span>
      </template>
      <template slot="o" slot-scope="_, record">
        <a-button @click="edit(record)" type="link" size="small">编辑</a-button>
        <a-button v-if="record.status != 0" @click="statusCar(record)" type="link" size="small">出库</a-button>
        <a-button v-if="!record.userId" @click="bindCar(record)" type="link" size="small">绑定</a-button>
        <!-- <a-button v-if="!record.isBlack" @click="addBlackList(record)" type="link" size="small">拉入黑名单</a-button> -->
      </template>
    </s-table>
    <Preview
      v-if="previewShow"
      :url-list="previewList"
      :onClose="closePreview"
    />
    <CarForm ref="CarForm" />
    <BindCar ref="BindCar" />
    <AddBlackList ref="AddBlackList" />
  </a-card>
</template>

<script>
import { TableSearch, STable } from '@/components'
import { getCarListAPI, editCarAPI, statusCarAPI, bindCarAPI, addBlackListAPI } from '@/api/car'
import { searchEmit, resetEmit } from '@/views/biz/common'
import CarForm from './modules/CarForm.vue'
import BindCar from './modules/BindCar.vue'
import AddBlackList from './modules/AddBlackList.vue'
import Preview from '@/components/Image/code/preview.vue'
import { downloadFile } from '@/utils/util'

let bodyOverflow = ''

export default {
  components: { TableSearch, STable, CarForm, Preview, BindCar, AddBlackList },
  data () {
    return {
      toolSettings: [
        { text: '导出全部车辆信息', icon: 'export', type: 'primary', click: this.export, loading: false }
      ],
      fields: [
        { field: 'number', type: 'input', label: '车牌号码', value: '', placeholder: '请输入车牌号码' },
        // { field: 'realname', type: 'input', label: '用户姓名', value: '', placeholder: '请输入' },
        { field: 'phone', type: 'input', label: '电话号码', value: '', placeholder: '请输入电话号码' },
        { field: 'status', type: 'select', label: '是否停放', value: undefined, placeholder: '请选择停放状态', options: [{ label: '空闲', value: 0 }, { label: '占用', value: 1 }] }
      ],
      columns: [
        { title: '车牌号码', dataIndex: 'number', width: 100, align: 'center', scopedSlots: { customRender: 'number' } },
        // { title: '用户姓名', dataIndex: 'realname', width: 100 },
        { title: '电话号码', dataIndex: 'phone', width: 120, align: 'center' },
        { title: '停放总次数', dataIndex: 'count', width: 120, align: 'center' },
        { title: '是否停放', dataIndex: 'status', width: 100, align: 'center', scopedSlots: { customRender: 'status' } },
        { title: '车辆颜色', dataIndex: 'color', width: 100, align: 'center' },
        { title: '车辆照片', dataIndex: 'images', width: 174, scopedSlots: { customRender: 'images' } },
        { title: '备注', dataIndex: 'note', width: 200, ellipsis: true },
        { title: '创建时间', dataIndex: 'createTime', width: 150, align: 'center' },
        { title: '更新时间', dataIndex: 'updateTime', width: 150, align: 'center' },
        { title: '其他操作', dataIndex: 'operation', align: 'center', width: 240, scopedSlots: { customRender: 'o' }, fixed: 'right' }
      ],
      tableData: query => {
        return getCarListAPI(Object.assign(query, this.params))
      },
      params: {
        number: '',
        realname: '',
        phone: '',
        status: undefined
      },
      previewShow: false,
      previewList: []
    }
  },
  methods: {
    searchEmit,
    resetEmit,
    onCompleted (rows) {
      rows.forEach(item => {
        item.images = item.images ? item.images.split(',') : []
      })
      return rows
    },
    rowClassName (record) {
      return record.isBlack ? 'black-car-row' : ''
    },
    /** @name 图片预览 **/
    imagePreview (url) {
      this.previewList = [url]
      if (this.previewShow) return
      bodyOverflow = document.body.style.overflow
      document.body.style.overflow = 'hidden'
      this.previewShow = true
    },
    /** @name 关闭预览 **/
    closePreview () {
      document.body.style.overflow = bodyOverflow
      this.previewShow = false
    },
    /** @name 编辑车位 **/
    edit (record) {
      this.$refs.CarForm.open('编辑车位', this.deepClone(record), (form, done) => {
        editCarAPI({
          ...form,
          images: form.images.join(','),
          id: record.id
        }).then(() => {
          this.$refs.table.refresh()
          this.$message.success('编辑成功')
          done(true)
        }).finally(() => {
          done(false)
        })
      })
    },
    /** @name 设置车辆出库 **/
    statusCar (record) {
      this.$confirm({
        title: '温馨提示',
        content: h => <div>确定把车辆（ <span style="color: #52c41a">{record.number}</span>）设置成<span style="color: #52c41a"> 出库 </span>状态？</div>,
        onOk: () => {
          statusCarAPI({
            id: record.id,
            number: record.number,
            status: 0
          }).then(() => {
            this.$refs.table.refresh()
            this.$message.success('设置成功')
          })
        }
      })
    },
    /** @name 导出 **/
    export () {
      this.$confirm({
        title: '温馨提示',
        content: '确定导出当前所有车辆信息吗？',
        onOk: () => {
          const target = this.toolSettings.find(item => item.text === '导出车辆')
          target.loading = true
          downloadFile('/car/export').then(() => {
            this.$message.success('导出成功')
          }).finally(() => {
            target.loading = false
          })
        }
      })
    },
    /** @name 绑定车主 **/
    bindCar (record) {
      record.userId = record.userId || undefined
      this.$refs.BindCar.open('绑定车主', this.deepClone(record), (form, done) => {
        bindCarAPI({
          id: record.id,
          userId: form.userId
        }).then(() => {
          this.$refs.table.refresh()
          this.$message.success('绑定成功')
          done(true)
        }).finally(() => {
          done(false)
        })
      })
    },
    /** @name 加入黑名单 **/
    addBlackList (record) {
      this.$refs.AddBlackList.open('加入黑名单', this.deepClone({ number: record.number, userId: record.userId }), (form, done) => {
        addBlackListAPI({
          number: record.number,
          userId: record.userId,
          note: form.note
        }).then(() => {
          this.$refs.table.refresh()
          this.$message.success('操作成功')
          done(true)
        }).finally(() => {
          done(false)
        })
      })
    }
  }
}
</script>

<style>
.black-car-row {
  background: #d5d5d5;
  background-image: repeating-linear-gradient(60deg,hsla(0,0%,100%,0.5),hsla(0,0%,100%,0.5) 15px,transparent 0,transparent 30px);
}
</style>
